const md5 = require('@/common/js-md5')

//排序的函数
function objKeySort(obj){
    //【1】用Object内置类的keys方法获取要排序对象的属性名
    //【2】用Array原型上的sort方法对获取的属性名进行排序，返回一个新数组newkey

    var newkey = Object.keys(obj).sort();

    var newObj = {}; //创建一个新的对象，用于存放排好序的键值对
    for(var i = 0; i < newkey.length; i++) { //遍历newkey数组
		
        if (isArray(obj[newkey[i]])){
            newObj[newkey[i]] = JSON.stringify(obj[newkey[i]]).replace(/[\\]/g, '')
        }else{
            newObj[newkey[i]] = obj[newkey[i]]
        } //向新创建的对象中按照排好的顺序依次增加键值对，
        //newObj[newkey[i].toLowerCase()] = obj[newkey[i]]; 并大写转换小写【做签名验证会用】
    }

    return newObj; //返回排好序的新对象
}
function isArray(obj){
    return(typeof obj== 'object') && obj.constructor == Array;
}

const ajax = (opt) => {
    opt = opt || {};
    opt.url = opt.url || '';
	let data=opt.data;
	let str="",d=opt.data;
	opt.method = opt.method || 'POST';
	let mid="61359";
	if(opt.method=="POST"){
		 var newObj=objKeySort(data);

		 str="{";
        for(let i in newObj){
            str+=`"${i}":"${newObj[i]}",`;
        }
        str=str.substr(0,str.length-1)
        str+="}&key=e3ebe304663e48639f3bfd4bb575ffd5";
        str = str.replace(/[\\]/g, '');
		d={
			appid:"",
			version:"",
			sign: md5(str).toUpperCase(),
			jsonParam:data,
			token:mid+""
		}
	}
    opt.header = opt.header || {
		"Content-Type": "application/json",
		//"Access-Control-Allow-Origin":"*",
		//"Content-Type":"application/x-www-form-urlencoded"
    };
    opt.success = opt.success || function () {};
	//http://wx.hnlxyj.com:8090 https://wx.hnlxyj.com:8443测试地址。https://wx.hnlxyj.com正式地址
	let url="";

	if(opt.host){
		url=opt.host+opt.url
	}else{
		url="https://wx.hnlxyj.com" + opt.url;
	}
    uni.request({
        url:url, 
		header: opt.header,
        data:d,
        method: opt.method,
		dataType: 'json',
        success: function (res) {
			//console.log(' uni.request',res)
			var data=res.data;
			if(data.code==200){
				opt.success(data.data);
			}else if(data.code=="-60007"){
				uni.showToast({
					title: "登录失效，2s后重新登录",
					icon:"none"
				})
	
			}else{
				uni.showToast({
					title: data.msg,
					icon:"none"
				})
				if(opt.fali){
					setTimeout(function(){
						opt.fail()
					},2000)
				}
			}
        },
        fail: function () {
            uni.showToast({
                title: '请稍后重试',
				icon:"none"
            });
        },
		complete:function(){ 
			
		}
    })
}
export default ajax
